package com.rtx.wms.customer.grp.upload;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.rtx.edi.platform.synctask.service.GatWayService;
import com.rtx.wms.customer.common.upload.UploadService;
import com.rtx.wms.std.common.bean.WmsConstant;

@SuppressWarnings("all")
public abstract class GRPUploadService implements UploadService{
	
	Logger log = LoggerFactory.getLogger(this.getClass());
	
	@Resource(name = "GrpGatWayService")
	GatWayService gatWayService;
	
	Map<Class,Map<String,Field>> cacheClassField = new HashMap<>();
	
	public void uploadHandle(Object data) {
		
		String method = resolveCallBackAPICode(data);
		
		String sourceJSON = JSON.toJSONString(data, SerializerFeature.WriteDateUseDateFormat);
		
		String result = gatWayService.handel(method, sourceJSON);
		
		resolveResonse(result,data);
	};

	protected abstract String resolveCallBackAPICode(Object data);
	
	
	//通过反射设置设置 标记字段ediflag,以及edimsg字段
	protected void resolveResonse(String response, Object data) {
		Map<String,Field> currentMap = null;
		Class clazz = data.getClass();
		if(cacheClassField.containsKey(clazz)) {
			currentMap = cacheClassField.get(clazz);
		}else {
			Map<String,Field> newCache = new HashMap<>();
			for(Field field:clazz.getDeclaredFields()) {
				
				if("ediflag".equals(field.getName())) {
					newCache.put("ediflag", field);
				};
				if("edimsg".equals(field.getName())) {
					newCache.put("edimsg", field);
				}
			}
			
			cacheClassField.put(clazz, newCache);
			
			currentMap = newCache;
		}
		
		Field ediflagField = currentMap.get("ediflag");
		Field edimsgField = currentMap.get("edimsg");
		
		
		try {
			JSONObject res = JSON.parseObject(response,JSONObject.class);
			String code = res.getString("code");
			if(!"200".equals(code)) {
				ediflagField.setAccessible(true);
				ediflagField.set(data, WmsConstant.FAIL_FLAG);
				ediflagField.setAccessible(false);
				
				edimsgField.setAccessible(true);
				edimsgField.set(data, res.getString("message"));
				edimsgField.setAccessible(false);
			}else {
				ediflagField.setAccessible(true);
				ediflagField.set(data, WmsConstant.SUCCESS_FLAG);
				ediflagField.setAccessible(false);
				
				edimsgField.setAccessible(true);
				edimsgField.set(data, res.getString("message"));
				edimsgField.setAccessible(false);
			}
		} catch (Exception e) {
			log.error("",e);
			try {
				ediflagField.setAccessible(true);
				ediflagField.set(data, WmsConstant.FAIL_FLAG);
				ediflagField.setAccessible(false);
				
				edimsgField.setAccessible(true);
				edimsgField.set(data, e.getMessage());
				edimsgField.setAccessible(false);
			} catch (Exception e2) {
				log.error("回传结果反射设-ediflag-edimsg-设置属性异常",e);
			}

		}
	}
}
